package com.ruoyi.system.util;

public class ChineseNumberConverter {
    private static final String[] CN_NUMBERS = {
            "零", "一", "二", "三", "四", "五", "六", "七", "八", "九"
    };
    private static final String[] CN_UNITS = {
            "", "十", "百", "千", "万", "十", "百", "千", "亿", "十", "百", "千", "兆"
    };

    public static String toChinese(int number) {
        if (number == 0) {
            return CN_NUMBERS[0];
        }

        StringBuilder result = new StringBuilder();
        boolean isNegative = number < 0;
        if (isNegative) {
            number = -number;
            result.append("负");
        }

        String numStr = String.valueOf(number);
        int length = numStr.length();

        for (int i = 0; i < length; i++) {
            int digit = numStr.charAt(i) - '0';
            int unitIndex = length - i - 1;

            // 处理数字
            if (digit != 0) {
                result.append(CN_NUMBERS[digit]);
                result.append(CN_UNITS[unitIndex]);
            } else {
                // 处理零
                // 1. 当前位为零，但后续还有非零数字，需要补零
                if (i < length - 1 && numStr.charAt(i + 1) != '0' &&
                        !result.toString().endsWith(CN_NUMBERS[0])) {
                    result.append(CN_NUMBERS[digit]);
                }
                // 2. 特殊单位：万、亿、兆
                else if (unitIndex % 4 == 0 && i > 0) {
                    // 确保单位前有非零数字
                    if (numStr.charAt(i - 1) != '0' ||
                            (i > 1 && numStr.charAt(i - 2) != '0') ||
                            (i > 2 && numStr.charAt(i - 3) != '0')) {
                        result.append(CN_UNITS[unitIndex]);
                    }
                }
            }
        }

        // 处理特殊情况：一十X → 十X
        if (result.toString().startsWith("一十") && result.length() > 2) {
            result.delete(0, 1);
        }

        return result.toString();
    }

    public static void main(String[] args) {
        System.out.println(toChinese(1));     // 输出：一
        System.out.println(toChinese(10));    // 输出：十
        System.out.println(toChinese(11));    // 输出：十一
        System.out.println(toChinese(20));    // 输出：二十
        System.out.println(toChinese(100));   // 输出：一百
        System.out.println(toChinese(108));   // 输出：一百零八
        System.out.println(toChinese(1234));  // 输出：一千二百三十四
        System.out.println(toChinese(10001)); // 输出：一万零一
        System.out.println(toChinese(100000001)); // 输出：一亿零一
        System.out.println(toChinese(-123));  // 输出：负一百二十三
    }
}